package com.fosun.sprcore.tools.generatecode.base;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import com.fosun.sprcore.tools.generatecode.utils.ExtFileUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class GcBaseTools {
	private Configuration cfg;

	protected void initFreeMaker() throws Exception {
		/*
		 * ----------------------------------------------------------------------
		 * --
		 */
		/* You should do this ONLY ONCE in the whole application life-cycle: */

		/* Create and adjust the configuration singleton */
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
		cfg.setDirectoryForTemplateLoading(new File("./template"));
		cfg.setDefaultEncoding("UTF-8");
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		cfg.setLogTemplateExceptions(false);
		this.cfg = cfg;
	}

	public void generate(String templateName, String outputFileName, Map data)
			throws Exception {
		outputFileName = "output/"+outputFileName;
		/* Get the template (uses cache internally) */
		Template temp = cfg.getTemplate(templateName);

		/* Merge data-model with template */
		// Writer out = new OutputStreamWriter(System.out);
		// temp.process(data, out);
		// Note: Depending on what `out` is, you may need to call `out.close()`.
		// This is usually the case for file output, but not for servlet output.

		//如果目录不存在，则创建
		File f = new File(outputFileName);
		File directory = new File(f.getParentFile().getAbsolutePath());
		if(!directory.exists()) {
			directory.mkdirs();
		}
		
		Writer out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(outputFileName), "UTF-8"));
		temp.process(data, out);
		out.flush();
		out.close();
		
		System.out.println("Generate File:output/"+outputFileName);
	}
	
	public void mkdir(String path){
		File fullPath = new File("output/"+path);
		if(!fullPath.exists()){
			fullPath.mkdirs();
		}
	}
	
	public static void clearOutput(){
		ExtFileUtils.deleteDirectory(new File("output/html"));
		new File("output/html").mkdir();
		ExtFileUtils.deleteDirectory(new File("output/java"));
		new File("output/java").mkdir();	
		ExtFileUtils.deleteDirectory(new File("output/mybatis"));
		new File("output/mybatis").mkdir();	
	}
}
